<template>
  <div class="ele-upload-image">
    <el-upload
      v-show="isShowUpload"
      v-model:file-list="fileList"
      :action="action"
      :headers="myHeaders"
      :list-type="listType"
      :style="{
        marginBottom: multiple && computedValues.length ? '20px' : '0px',
      }"
      :disabled="uploading"
      :multiple="multiple"
      :show-file-list="false"
      :limit="limit"
      :before-upload="handleBeforeUpload"
      :on-change="handleChange"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
    >
      <div v-if="listType === 'picture-card'" v-loading="uploading">
        <template>
          <div
            :style="{
              width: size + 'px',
              height: size + 'px',
              lineHeight: size + 'px',
            }"
          >
            <i class="el-icon-plus"></i>
          </div>
        </template>
      </div>
      <div v-if="listType === 'text'" class="up-btn">
        <el-button>点击上传</el-button>
      </div>
      <div v-if="listType === 'picture'" class="up-btn">
        <el-button>点击上传</el-button>
      </div>
      <template #tip>
        <div v-if="isShowTip && listType === 'text'" class="el-upload__tip">
          只能上传
          <b style="color: #f56c6c">{{
            fileType ? fileType.join(' / ') : '图片'
          }}</b>
          格式文件且为文件白名单支持的格式，且大小不超过
          <b style="color: #f56c6c">{{ fileSize }}Mb</b>
        </div>
        <div v-if="isShowTip && listType === 'picture'" class="el-upload__tip">
          只能上传
          <b style="color: #f56c6c">{{
            fileType ? fileType.join(' / ') : '图片'
          }}</b>
          格式图片且为文件白名单支持的格式<b style="color: #f56c6c"
            >{{ limit }}张</b
          >，且大小不超过
          <b style="color: #f56c6c">{{ fileSize }}Mb</b>
        </div>
      </template>
      <div v-if="showRules">
        <p class="upload-rules">{{ rulesText }}</p>
      </div>
    </el-upload>
    <ele-gallery
      :lazy="lazy"
      :remove-fn="handleRemove"
      :size="size"
      :source="value"
      :title="title"
      :show-name="showName"
    />
  </div>
</template>

<script setup name="uploadImg">
import EleGallery from './eleGallery'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const store = useStore()
const props = defineProps({
  // 上传地址 (同官网)
  action: {
    type: String,
    required: true,
  },
  // 是否显示列表
  showName: {
    type: Boolean,
    default: false,
  },
  // 文件列表的类型
  listType: {
    type: String,
    default: 'picture-card',
  },
  value: {
    type: [String, Array],
    default() {
      return []
    },
  },
  // 是否支持多选文件 (同官网)
  multiple: {
    type: Boolean,
    default: false,
  },
  // 响应处理函数
  responseFn: Function,
  // 弹窗标题
  title: String,
  // 支持上传的文件类型
  fileType: {
    type: Array,
    default() {
      return ['png', 'jpg', 'jpeg', 'pdf']
    },
  },
  // fileSize: {
  //   type: Number,
  //   default: 5
  // },
  limit: {
    type: Number,
    default: 2,
  },
  showRules: {
    //上传规则
    type: Boolean,
    default: false,
  },
  rulesText: {
    type: String,
    default:
      '上传规则：以编码作为图片名称，同一编码上传多个图片，用编码+@#1，编码+@#2，同一编码的数字依次叠加\n例：编码a.png，编码a@#1.png，编码a@#2.png\n\xa0\xa0\xa0\xa0\xa0\xa0\xa0编码b.png，编码b@#1.png，编码b@#2.png',
  },
})

const fileSize = ref(proxy.$store.state.permission.systemConfig.max_file_size)
const uploading = ref(false)
const lazy = ref(true)
const isShowTip = ref(true)
const size = ref(150)
const myHeaders = ref({
  Authorization: '',
})
const fileList = ref([])
const computedValues = computed(() => {
  if (props.value) {
    if (typeof props.value === 'string') {
      return [props.value]
    } else {
      return props.value
    }
  } else {
    return []
  }
})
const isShowUpload = computed(() => {
  if (props.multiple) {
    return true
  } else {
    return computedValues.value.length === 0
  }
})
const successFiles = computed(() => {
  return fileList.value.filter((file) => file.status === 'success')
})
const token = computed(() => {
  return proxy.$store.state.user.token
})

watch(
  () => props.value,
  (val) => {
    console.log(val)
  }
)

function handleBeforeUpload(file) {
  if (props.value && props.value.length >= props.limit) {
    proxy.$message.error({
      message: `最多上传${props.limit}个文件`,
      showClose: true,
      duration: 3500,
    })
    return
  } else {
    let isImg = false
    if (props.fileType) {
      isImg = props.fileType.some(
        (type) => file.name.split('.')[file.name.split('.').length - 1] === type
      )
    } else {
      isImg = file.type.indexOf('image') > -1
    }
    const isLt = file.size / 1024 / 1024 < fileSize.value

    if (!isImg) {
      proxy.$message.error({
        message: `文件格式不正确, 请上传 ${props.fileType.join(
          ' / '
        )} 格式文件!`,
        showClose: true,
        duration: 3500,
      })
      return false
    }

    let file_type_list = proxy.$store.state.permission.dict['file_type_list']
    if (file_type_list && file_type_list.length) {
      let uploadType = file.name.split('.')[file.name.split('.').length - 1]
      let file_type_list_arr = []
      file_type_list.forEach((item) => {
        file_type_list_arr.push(item.code)
      })
      if (!String(file_type_list_arr).includes(uploadType)) {
        proxy.$message.error({
          message: `文件格式【${uploadType}】非白名单文件类型格式，不支持上传`,
          showClose: true,
          duration: 3500,
        })
        return false
      }
    }

    if (!isLt) {
      proxy.$message.error({
        message: `上传文件大小不能超过 ${fileSize.value} MB!`,
        showClose: true,
        duration: 3500,
      })
      return false
    }
    uploading.value = true
    // if(isImg && isLt){
    //     let fd = new FormData();
    //     fd.append("files", file)
    //     this.$ajax({
    //         method: "post",
    //         url: this.action,
    //         data: fd
    //     }).then( res => {
    //         if(res.success){
    //             // res.data.forEach( item => {
    //             //     item = this.$ajax.defaults.baseURL + '/core/systemTools/' + item;
    //             // })
    //             this.handleUploadSuccess(res.data[0], file);
    //
    //         }else {
    //             this.handleUploadError()
    //         }
    //     })
    // }
    return isImg && isLt
  }
}
function handleChange(file, fileList) {
  uploading.value = false
  fileList.value = fileList
}
// 文件个数超出
function handleExceed(files, fileList) {
  proxy.$message.error({
    message: `最多上传${props.limit}个文件`,
    duration: 3500,
    showClose: true,
  })
}
// 上传失败
function handleUploadError(err) {
  if (props.value.length >= props.limit) {
    return
  }
  uploading.value = false
  proxy.$message.error({
    message: '上传失败, 请重试',
    duration: 3500,
    showClose: true,
  })
  proxy.$emit('error', err)
}
// 上传成功回调
function handleUploadSuccess(response, file) {
  if (props.value && props.value.length >= props.limit) {
    return
  }
  uploading.value = false
  if (response.success) {
    proxy.$message.success({
      message: '上传成功',
      duration: 3500,
      showClose: true,
    })
    file.filePath = response.data[0]
    if (props.responseFn) {
      file = props.responseFn(file, successFiles.value)
    }
    if (props.multiple) {
      if (Array.isArray(props.value)) {
        emits('update:value', [...props.value, file[file.length - 1]])
      } else {
        emits('update:value', [file])
      }
    } else {
      emits('update:value', [file])
    }
  } else {
    proxy.$message.error({
      message: response.msg,
      duration: 3500,
      showClose: true,
    })
  }
}
function handleRemove(index) {
  if (props.multiple) {
    const data = [...computedValues.value]
    data.splice(index, 1)
    if (fileList.value && fileList.value.length) {
      fileList.value.splice(index, 1)
    }
    emits('update:value', data || [], index)
  } else {
    fileList.value = []
    emits('update:value', null)
  }
}
onMounted(() => {
  myHeaders.value.Authorization = token.value
})
</script>

<style scoped>
.ele-upload-image {
  line-height: 1;
}
.ele-upload-image .el-loading-spinner {
  line-height: 1;
}
.ele-upload-image .el-icon-plus {
  vertical-align: middle;
}
.ele-upload-image .el-upload--picture-card {
  width: auto;
  height: auto;
  background: none;
  line-height: inherit;
}
.up-btn {
  display: flex;
  align-items: center;
}
.el-upload__tip {
  padding-left: 10px;
}
.upload-rules {
  text-align: left;
  padding-top: 5px;
  padding-bottom: 5px;
  line-height: 22px;
  white-space: pre-line;
}
</style>
